package com.config;

import java.util.LinkedHashMap;
import java.util.Map;

import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 过滤配置
 * 
 * @author Administrator
 *
 */
@Configuration
public class ShiroConfiguration {

	/**
	 * Filter 设置对应的过滤条件和跳转条件
	 */
	@Bean
	public ShiroFilterFactoryBean shirFilter(org.apache.shiro.mgt.SecurityManager securityManager) {
		ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
		// 必须设置 SecurityManager
		shiroFilterFactoryBean.setSecurityManager(securityManager);

		Map<String, String> filterChainDefinitionMap = new LinkedHashMap<String, String>();
		// 配置不会被拦截的链接 顺序判断
		filterChainDefinitionMap.put("/static/**", "anon");
		filterChainDefinitionMap.put("/", "user");
		filterChainDefinitionMap.put("/**", "authc");
		// 如果不设置默认会自动寻找Web工程根目录下的"/login.jsp"页面
		// 访问的是后端url地址为 /login的接口
		shiroFilterFactoryBean.setLoginUrl("/userShiro/login");
		// 登录成功后要跳转的链接
		shiroFilterFactoryBean.setSuccessUrl("/userShiro/index");
		shiroFilterFactoryBean.setUnauthorizedUrl("/userShiro/403");
		filterChainDefinitionMap.put("/logout", "logout");

		//配置访问权限
//	    filterChainDefinitionMap.put("/", "anon"); 
	    filterChainDefinitionMap.put("/userShiro/login", "anon");
	    filterChainDefinitionMap.put("/logout", "logout"); 
	    filterChainDefinitionMap.put("/news/**", "authc,roles[news]");
	    filterChainDefinitionMap.put("/audio/**", "authc,roles[audio]"); 
	    filterChainDefinitionMap.put("/album/**", "authc,roles[audio]"); 
		// 过滤链定义，从上向下顺序执行，一般将 /**放在最为下边
		// <!-- authc:所有url都必须认证通过才可以访问; anon:所有url都可以匿名访问-->
		
		shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
		System.out.println("Shiro拦截器工厂类注入成功");
		return shiroFilterFactoryBean;
	}

	/**
	 * 将自定义的realm加入容器
	 */
	@Bean(name = "myShiroRealm")
	public MyShiroRealm myShiroRealm() {
		return new MyShiroRealm();
	}
	
	@Bean(name = "securityManager")
	public DefaultWebSecurityManager securityManager() {
		DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
		securityManager.setRealm(myShiroRealm());
		return securityManager;
	}
}
